package com.lsh.aspectj;

import com.lsh.anno.DataSource;
import com.lsh.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 多数据源处理
 * 注解@Order或者接口Ordered的作用是定义Spring IOC容器中Bean的执行顺序的优先级，
 * 而不是定义Bean的加载顺序，Bean的加载顺序不受@Order或Ordered接口的影响；
 * 默认是最低优先级,值越小优先级越高
 * @author ruoyi
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.lsh.anno.DataSource) || @within(com.lsh.anno.DataSource)")
    public void dsPointCut() {

    }

    /**
     * JoinPoint用来获取代理类和被代理类的信息
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("切换数据源——环绕前");
        DataSource dataSource = getDataSource(point);

        if (dataSource != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        }
        finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
            System.out.println("切换数据源——环绕后");
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public DataSource getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        //signature.getMethod() 获得当前切入点的方法名
        //AnnotationUtils.findAnnotation（）查找当前方法中时候包含@DataSource注解，如果有就返回此注解，如果没有就返回空
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource;
        }
        //signature.getDeclaringType() 获得切入点的类对象
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}
